﻿namespace ZyGame.Event
{
    using System;
    using System.Collections.Generic;

    sealed class GameEventHandler
    {
        class ActionUnlit
        {
            public bool isOnce;
            public Action<object> callback;
        }

        private List<ActionUnlit> actions = new List<ActionUnlit>();

        public void Add(Action<object> action, bool isOnce)
        {
            actions.Add(new ActionUnlit { callback = action, isOnce = isOnce });
        }

        public void Remove(Action<object> action)
        {
            ActionUnlit unlit = actions.Find(x => x.callback.Equals(action));
            if (unlit is null)
            {
                return;
            }

            actions.Remove(unlit);
        }

        public void OnTigger(object args)
        {
            for (int i = actions.Count - 1; i >= 0; i--)
            {
                Unsafe(actions[i], args);
                if (actions[i].isOnce)
                {
                    actions.Remove(actions[i]);
                }
            }
        }

        private void Unsafe(ActionUnlit unlit, object args)
        {
            try
            {
                unlit.callback(args);
            }
            catch (Exception e)
            {
                Client.Console.WriteError(e);
            }
        }
    }
}